package com.example.itshome.network;

import android.app.Activity;
import android.widget.TextView;
import com.example.itshome.util.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

public class SendVerifyCodeRequest extends AbstractNetworkRequest{

    private String email;
    private TextView sendCodeTextView;

    public SendVerifyCodeRequest setSendCodeTextView(TextView sendCodeTextView) {
        this.sendCodeTextView = sendCodeTextView;
        return this;
    }

    public SendVerifyCodeRequest setEmail(String email) {
        this.email = email;
        return this;
    }

    public SendVerifyCodeRequest(Activity activity) {
        super(activity);
    }

    @Override
    protected String getPathAndParams() {
        return "mail/register-code?email="+email;
    }

    @Override
    protected void handleResult(String result) {
        try {
            JSONObject jsonObject=new JSONObject(result);
            int code=jsonObject.getInt("code");
            if(code!=200){
                return;
            }
            setHandleResultRunnable(new Runnable() {
                @Override
                public void run() {
                    //60秒后才能再次发送验证码
                    TimerTask task=new TimerTask() {
                        private int count=60;
                        @Override
                        public void run() {
                            count--;
                            String s;
                            if(count==-1){
                                this.cancel();
                                s="发送验证码";
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        sendCodeTextView.setClickable(true);
                                    }
                                });
                            }else {
                                s="等待"+count+"秒后重发";
                            }
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sendCodeTextView.setText(s);
                                }
                            });
                        }
                    };
                    new Timer().schedule(task,0,1000);
                    ToastUtil.showToast("验证码发送成功",activity);
                    sendCodeTextView.setClickable(false);
                }
            });
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
}
